package com.dai.train.common.controller;

import com.dai.train.common.exception.BusinessException;
import com.dai.train.common.resp.CommonResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理类
 */
@RestControllerAdvice
public class CommonExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(CommonExceptionHandler.class);


    @ExceptionHandler(value = Exception.class)
    public CommonResp CustomerExceptionHandler(Exception e){

        CommonResp<Object> resp = new CommonResp<>();
        LOG.error("系统异常:",e);
        resp.setMessage("系统出现异常，请联系管理员");
        resp.setSuccess(false);
        return resp;
    }

    @ExceptionHandler(value = BusinessException.class)
    public CommonResp BusinessExceptionHandler(BusinessException e){

        CommonResp<Object> resp = new CommonResp<>();
        LOG.error("业务异常: {}",e.getBusinessExceptionEnum().getDesc());
        resp.setMessage(e.getBusinessExceptionEnum().getDesc());
        resp.setSuccess(false);
        return resp;
    }

    @ExceptionHandler(value = BindException.class)
    public CommonResp BusinessExceptionHandler(BindException e){

        CommonResp<Object> resp = new CommonResp<>();
        // 组装异常信息
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuffer stringBuffer = new StringBuffer();
        for (ObjectError allError : allErrors) {
            stringBuffer.append(allError.getDefaultMessage() + " ");
        }
        LOG.error("校验异常: {}",stringBuffer.toString());
        resp.setMessage(stringBuffer.toString());
        resp.setSuccess(false);
        return resp;
    }
 }
